import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import TreeSelector from '@/components/TreeSelector';
import { useRequest } from '@/hooks';
import { message } from 'antd';
import { getFunctionalList, getOrganizationList } from '@/services/Organization/orgmanage';
import { filterUsefulRequestParams } from '@/utils/request';

const parseData = data => {
    const result = [];
    data.forEach(item => {
        const newItem = {
            ...item,
            id: item.organizationPath,
            pId: item.parentOrganizationPath,
            title: item.organizationName,
            selectable: false,
            hasDataPermission: item.organizationPermissions !== 0
        };
        result.push(newItem);
    });
    return result;
};

export const useFetchOrganizationData = (isFunctional, config) => {
    const { param = {}, useCache = true, ...otherProps } = config || {};
    const cacheConfig = useCache
        ? {
              cacheKey: `org-data-${isFunctional ? 'functional' : ''}-${Object.values(param || {}).join('-')}`,
              staleTime: 60000 // 1分钟
          }
        : {};
    return useRequest(() => (isFunctional ? getFunctionalList(param) : getOrganizationList(param)), {
        ...cacheConfig,
        ready: param?.organizationCode,
        refreshDeps: [param?.organizationCode],
        formatResult: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    return parseData(res.data);
                }
                message.error(msg);
            }
            return undefined;
        },
        ...otherProps
    });
};

const preprocessDataItem = (array, { isNeedPermission, isFunctional }) =>
    array?.map(item => {
        const obj = { ...item };
        // 如果没有数据权限，不可选择
        if (obj.organizationPermissions === 0 && isNeedPermission === true) {
            obj.disabled = true;
            obj.selectable = false;
        }
        if (obj?.children?.length) {
            obj.children = preprocessDataItem(obj.children, {
                isNeedPermission,
                isFunctional
            });
        }
        if (isFunctional && (obj.organizationType === 1 || obj.organizationType === 2)) {
            // 组织机构下不能选择集团和公司
            obj.disabled = true;
            obj.selectable = false;
        }
        if (!isFunctional && obj.organizationType === 3) {
            // 行政机构下不能选择部门
            obj.disabled = true;
            obj.selectable = false;
        }
        return obj;
    });

/**
 * 机构选择组件
 */
const OrganizationSelector = React.forwardRef((props, ref) => {
    const {
        data: outerData,
        loading: outerLoading,
        placeholder,
        organizationCode,
        treeCheckStrictly,
        isFunctional,
        isNeedPermission,
        isDisableAuditData,
        isStatisticsChildren,
        isIgnoreOptionDisabled,
        ...otherProps
    } = props;
    const placeholderValue = placeholder || (isFunctional ? '请选择组织机构' : '请选择行政机构');
    // 获取数据
    const { data = outerData, loading } = useFetchOrganizationData(isFunctional, {
        ready: !outerData,
        param: filterUsefulRequestParams({
            organizationCode,
            showTreeFlag: 0
        })
    });
    const processedData = useMemo(
        () =>
            preprocessDataItem(data, {
                isNeedPermission,
                isFunctional
                // isStatisticsChildren
            }) || [],
        [data, isFunctional, isNeedPermission]
    );
    return (
        <TreeSelector
            ref={ref}
            data={processedData}
            loading={outerLoading ?? loading}
            treeCheckStrictly
            placeholder={placeholderValue}
            optionKeyProp="organizationPath"
            optionValueProp="organizationCode"
            optionLabelProp="organizationName"
            optionPidProp="parentOrganizationPath"
            {...otherProps}
        />
    );
});

OrganizationSelector.propTypes = {
    /** 占位符 */
    placeholder: PropTypes.string,
    /** 是否禁用组件 */
    disabled: PropTypes.bool,
    /** 不渲染触发器, 编码方式控制弹框展示 */
    manual: PropTypes.bool,
    /** 可选的最大数量, multiple: true 情况下可用 */
    max: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
    /** 是否使用弹框的交互形式 */
    modal: PropTypes.bool,
    /** 是否是多选 */
    multiple: PropTypes.bool,
    /** 结果预览是否开启分组展示. multiple: true 情况下可用 */
    isPreviewByGroup: PropTypes.bool,
    /** 结果的排序, 默认是 desc. multiple: true 情况下可用 */
    previewSortType: PropTypes.oneOf(['asc', 'desc']),
    /** 指定机构编码 */
    organizationCode: PropTypes.string,
    /** 是否需要数据权限, 默认为 false. (权限与用户和模块相关, 新的业务需要申请数据权限, 可以联系公共服务组的服务端的伙伴配置) */
    isNeedPermission: PropTypes.bool
    /** 是否统计子节点, 默认为 false */
    // isStatisticsChildren: PropTypes.bool
};
OrganizationSelector.defaultProps = {
    placeholder: null,
    disabled: false,
    manual: false,
    max: false,
    modal: false,
    multiple: false,
    isNeedPermission: false,
    // isStatisticsChildren: false,
    isPreviewByGroup: false,
    previewSortType: 'desc',
    organizationCode: null
};
OrganizationSelector.displayName = 'OrganizationSelector';

export default OrganizationSelector;
